/**
 * 基础图表组件
 * 封装echarts通用逻辑,提供基础配置
 */
<template>
  <div class="base-chart" ref="chartContainer"></div>
</template>

<script>
import * as echarts from 'echarts';
import { STOCK_CHART_OPTIONS } from '@/constants/chart';

export default {
  name: 'BaseChart',

  props: {
    // 图表配置项
    options: {
      type: Object,
      required: true
    },
    // 图表高度
    height: {
      type: String,
      default: '400px'
    }
  },

  data() {
    return {
      chart: null
    };
  },

  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.destroyChart();
  },

  methods: {
    /**
     * 初始化图表
     */
    initChart() {
      if (!this.$refs.chartContainer) return;

      this.chart = echarts.init(this.$refs.chartContainer);
      this.updateChart();
    },

    /**
     * 更新图表配置
     */
    updateChart() {
      if (!this.chart) return;

      const options = {
        ...STOCK_CHART_OPTIONS,
        ...this.options
      };

      this.chart.setOption(options);
    },

    /**
     * 处理窗口大小变化
     */
    handleResize() {
      this.chart?.resize();
    },

    /**
     * 销毁图表实例
     */
    destroyChart() {
      this.chart?.dispose();
      this.chart = null;
    }
  },

  watch: {
    options: {
      handler() {
        this.$nextTick(() => {
          this.updateChart();
        });
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.base-chart {
  width: 100%;
  height: v-bind(height);
}
</style> 